<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入商品名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商品价格" prop="price">
        <el-input v-model="queryParams.price" placeholder="请输入商品价格" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商品类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择商品类型">
          <el-option v-for="item in commodityType" :key="item.id" :label="item.name" :value="item.name"
            @keyup.enter.native="handleQuery"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <div>
      <el-col :span="2">
        <h4>{{ this.shopName }}</h4>
      </el-col>
      <!-- <el-col :span="10">
        <h4>{{ this.showInfo }}</h4>
      </el-col> -->
      <el-col :span="10">
        <el-button type="primary" style="left" icon="el-icon-shopping" size="small"
          @click="placeOrderInfo()">下单</el-button>
        <el-button type="primary" icon="el-icon-shopping" size="small" @click="handleAdd()">查看购物车</el-button>
      </el-col>
    </div>

    <el-table v-loading="loading" :data="commodityList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="图片" align="center" prop="image" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="center" prop="name" />
      <el-table-column label="商品类型" align="center" prop="type" />
      <el-table-column label="商品数量" align="center" prop="number" />
      <el-table-column label="商品价格" align="center" prop="price" />
      <el-table-column label="所属门店" align="center">{{ this.shopName }}</el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="addShopCommodity(scope.row)">+</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="subtractShopCommodity(scope.row)">-</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-table v-loading="loading" :data="commodityListInfo" @selection-change="handleSelectionChange">
        <el-table-column label="图片" align="center" prop="image" width="100">
          <template slot-scope="scope">
            <image-preview :src="scope.row.image" :width="50" :height="50" />
          </template>
        </el-table-column>
        <el-table-column label="商品名称" align="center" prop="name" />
        <el-table-column label="商品类型" align="center" prop="type" />
        <el-table-column label="商品数量" align="center" prop="number" />
        <el-table-column label="商品价格" align="center" prop="price" />
        <el-table-column label="所属门店" align="center">{{ this.shopName }}</el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="addShopCommodity(scope.row)">+</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete"
              @click="subtractShopCommodity(scope.row)">-</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div> -->
    </el-dialog>
  </div>
</template>

<script>
import { listCommodity, getCommodity, delCommodity, addCommodity, updateCommodity, placeOrder } from "@/api/system/commodity";

export default {
  name: "Commodity",
  data() {
    return {
      commodityType: [
        { name: '蔬菜', id: '1' },
        { name: '日常用品', id: '2' },
        { name: '厨具', id: '3' },
        { name: '零食', id: '4' }
      ],
      showInfo: '总金额为:0',
      CommodityAllMoney: 0,
      commodityListInfo: [],
      placeOrder: {},
      shopName: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品表格数据
      commodityList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        number: null,
        price: null,
        image: null,
        ownerShop: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {

    this.shopName = localStorage.getItem('shopName')
    if (localStorage.getItem("shopId") != null || localStorage.getItem("shopId") != '') {
      this.queryParams.ownerShop = localStorage.getItem("shopId");
    } else {
      this.queryParams.ownerShop = ''
    }

    this.getList();
  },
  methods: {
    /** 查询商品列表 */
    getList() {
      this.loading = true;
      if (localStorage.getItem("shopId") != null || localStorage.getItem("shopId") != '') {
        this.queryParams.ownerShop = localStorage.getItem("shopId");
      }
      this.queryParams.roles = localStorage.getItem("roles")
      listCommodity(this.queryParams).then(response => {
        this.commodityList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.getList();
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        number: null,
        price: null,
        image: null,
        ownerShop: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "购物车";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCommodity(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品";
      });
    },
    /** 添加商品 */
    addShopCommodity(row) {
      if (this.commodityListInfo.length == 0) {
        if (row.number > 0) {
          var info = {};
          info.id = row.id;
          info.name = row.name;
          info.number = 1;
          info.price = row.price;
          info.image = row.image;
          info.type = row.type;
          this.commodityListInfo.push(info)
          this.$modal.msgSuccess("添加到购物车中");

        } else {
          this.$modal.msgSuccess("商店没有更多该商品了！");
          return;
        }
      } else {
        if (row.number <= 0) {
          this.$modal.msgSuccess("商店没有更多该商品了！");
          return ;
        }
        var result = false;
        this.commodityListInfo.forEach(item => {
          if (item.id === row.id) {
            result = true;
            if (row.number <= item.number) {
              this.$modal.msgSuccess("商店没有更多该商品了！");
              // item.number = item.number - 1
              item.number = row.number;
              return;
            }
            // if(row.number == item.number){
            //   this.$modal.msgSuccess("商店没有更多该商品了！");
            //   return;
            // }
            item.number = item.number + 1
            this.$modal.msgSuccess("添加到购物车中");

          }
        })

        if (!result) {
          var info = {};
          info.id = row.id;
          info.name = row.name;
          info.number = 1;
          info.price = row.price;
          info.image = row.image;
          info.type = row.type;
          this.commodityListInfo.push(info)
          this.$modal.msgSuccess("添加到购物车中");

        }
      }
      // this.showShopCommodity();
      console.log(JSON.stringify(this.commodityListInfo))
    },
    /** 移除商品 */
    subtractShopCommodity(row) {
      var flag = false;
      if (this.commodityListInfo.length == 0) {
        this.$modal.msgSuccess("您的购物里没有该商品");
        return;
      } else {
        this.commodityListInfo.forEach((item, index) => {
          if (item.id == row.id) {
            flag = true;
            if (item.number <= 1) {
              this.commodityListInfo.splice(index, 1)
            } else {
              item.number = item.number - 1
            }
          }
        })
        if (!flag) {
          this.$modal.msgSuccess("您的购物里没有该商品");
          return;
        }
      }
      // this.showShopCommodity();
      console.log(JSON.stringify(this.commodityListInfo))
    },
    /**展示数据*/
    showShopCommodity() {
      this.showInfo = '';
      var allMoney = 0;
      this.commodityListInfo.forEach(item => {
        this.showInfo = this.showInfo + "商品名:" + item.name + '  数量:' + item.number + "  ---  ";
        allMoney = allMoney + (item.price * item.number);
      })
      this.showInfo = this.showInfo + '   总金额为:' + allMoney;
      this.CommodityAllMoney = allMoney;
      console.log(JSON.stringify(this.showInfo))

    },
    placeOrderInfo() {
      if (this.commodityListInfo.length == 0) {
        this.$modal.msgSuccess("您的购物里没有商品!");
      }
      this.placeOrder.allMoney = this.CommodityAllMoney;
      this.placeOrder.shopId = localStorage.getItem("shopId");
      this.placeOrder.commodities = this.commodityListInfo;
      this.placeOrder.shopName = localStorage.getItem("shopName")
      placeOrder(this.placeOrder).then(response => {
        console.log(JSON.stringify(response))
        this.$modal.msgSuccess("下单成功");
        this.getList();
        this.commodityListInfo = []
        this.placeOrder = {}
        this.showShopCommodity()
      })
      this.placeOrder = {};
      this.commodityListInfo = [];
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        this.form.ownerShop = localStorage.getItem("shopId");
        if (valid) {
          if (this.form.id != null) {
            updateCommodity(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCommodity(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除商品编号为"' + ids + '"的数据项？').then(function () {
        return delCommodity(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/commodity/export', {
        ...this.queryParams
      }, `commodity_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
